// pages/editor/editor.js

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  editor: null,

  initEditor () {
    let query = wx.createSelectorQuery()
    return new Promise((rv, rj) => {
      query.select('#editor')
      .context(res => {
        this.editor = res.context
        rv(this.editor)
      })
      .exec()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (!this.editor) {
      this.initEditor()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  async uploadImage () {
    try {
      let ret = await new Promise((rv, rj) => {
        wx.chooseMedia({
          count: 1,
          mediaType: ['image'],
          sourceType: ['album', 'camera'],
          sizeType: ['original', 'compressed'],
          success: res => {
              rv(res)
          },
          fail: err => {
            rj(err)
          }
        }) // end chooseMedia
      })
    
      console.log(ret.tempFiles[0].tempFilePath);

      this.editor.insertImage({
        src: ret.tempFiles[0].tempFilePath
      })
      } catch (err) {
        console.error(err)
      }
  },

  redo () {
    this.editor.redo()
  },

  undo () {
    this.editor.undo()
  },

  clearFormat () {
    this.editor.removeFormat({
      fail: (err) => { console.error(err) }
    })
  },

  postData (e) {
    console.log(e.detail.value)
    let content = ''
    this.editor.getContents({
      success: res => {
        content = res.html
        console.log(content)
        wx.request({
          url: 'http://localhost:3000/community/storage',
          method:"POST",
          data: {
            detail: res.html,
            openid: app.globalData.openid,
            time: new Date().getTime()
          },
          header: {
            authorzation: wx.getStorageSync("token")
          },
          success: res => {
            console.log(res);
            wx.switchTab({
              url: '../community/community',
            })
          }
        })
      }
    })
  },

  timer: null,

  cacheContent () {
    if (this.timer) return

    this.timer = setTimeout(() => {
      this.editor.getContents({
        success: res => {
          wx.setStorageSync('editorContent', res.html)
        }
      })
      this.timer = null
    }, 500)
  },

})